import 'package:cloud_medicine/components/above_loading.dart';
import 'package:cloud_medicine/components/close_circle.dart';
import 'package:cloud_medicine/components/util.dart';
import 'package:cloud_medicine/http/config.dart';
import 'package:cloud_medicine/http/post_api.dart';
import 'package:cloud_medicine/model/post_detail.dart';
import 'package:cloud_medicine/pages/image_show.dart';
import 'package:flutter/material.dart';
import 'dart:io';
import 'package:image_picker/image_picker.dart';

class EditPost extends StatefulWidget {
  final int postID;

  EditPost({Key key, this.postID}) : super(key: key);

  @override
  _EditPostState createState() => _EditPostState();
}

class _EditPostState extends State<EditPost> {
  bool _loading = false;
  PostDetailInfo _postDetail;
  TextEditingController controller = TextEditingController();
  final picker = ImagePicker();
  List<dynamic> postImages = []; // 帖子内有的图片列表
  DateTime lastPopTime; //上次点击时间

  @override
  void initState() {
    super.initState();
    _init();
  }

  Future<Null> _init() async {
    if (widget.postID == null) {
      return;
    }
    setState(() {
      _loading = true;
    });
    dynamic res = await getPost_api('$backIP/post/getPostDetail', {
      'id': widget.postID,
    });
    if (mounted) {
      setState(() {
        if (res['code'] == 0) {
          _postDetail = PostDetailInfo.init(res['data']);
        } else {
          errorToast(res['message']);
        }
        _loading = false;
      });
      controller.text = _postDetail.content;
      postImages = _postDetail.files;
    }
  }

  // 生成gridView的网格视图图片
  List<Widget> getWidgetList() {
    List<Widget> filesListShow = [];
    for (int i = 0; i < postImages.length; i++) {
      filesListShow.add(getItemContainer(postImages[i], i));
    }
    // 增加最后的一个添加图片的图标
    filesListShow.add(GestureDetector(
      onTap: pickImage,
      child: Container(
        width: 50,
        height: 50,
        decoration: BoxDecoration(
            border: Border.all(width: 1, color: Colors.lightBlueAccent)),
        child: Icon(Icons.add, color: Colors.lightBlueAccent),
      ),
    ));
    return filesListShow;
  }

  // 生成每一张图片的样式
  Widget getItemContainer(String file, int index) {
    return GestureDetector(
      child: Container(
        child: Stack(
          children: <Widget>[
            Align(
              child: FadeInImage.assetNetwork(
                placeholder: 'images/loading.gif', // 占位图
                image: file,
              ),
              alignment: Alignment.center,
            ),
            Align(
              child: CloseCircle(index: index, callback: deleteImage),
              alignment: Alignment(0.9, -0.9),
            )
          ],
        ),
        color: Colors.grey[100],
      ),
      onTap: () {
        Navigator.of(context).push(MaterialPageRoute(
            builder: (context) => ImageShow(
                  url: file,
                  isFile: false,
                )));
      },
    );
  }

  // 删除图片
  void deleteImage(int index) {
    setState(() {
      postImages.removeAt(index);
    });
  }

  // 在底部显示图片选取方式
  pickImage() {
    showModalBottomSheet(
        context: context,
        builder: (context) => Container(
              height: 120,
              child: Column(
                children: <Widget>[_item('拍照', true), _item('从相册选择', false)],
              ),
            ));
  }

  // 在底部生成每一项部件
  _item(String title, bool isTakePhoto) {
    return GestureDetector(
      child: ListTile(
        leading: Icon(isTakePhoto ? Icons.camera_alt : Icons.photo_library),
        title: Text(title),
        onTap: () => getImage(isTakePhoto),
      ),
    );
  }

  // 拍照或从图库中选取图片
  Future getImage(bool isTakePhoto) async {
    Navigator.pop(context);
    final pickedFile = await picker.getImage(
        source: isTakePhoto ? ImageSource.camera : ImageSource.gallery);

    showDialog(
        context: context,
        builder: (context) {
          return new AboveLoading();
        });
    await upLoadImage(File(pickedFile.path), (imageUrl) {
      setState(() {
        postImages.add(imageUrl);
      });
      Navigator.pop(context);
    });
  }

  // 判断loading并且在loading为false时渲染主要视图
  Widget _childLayout() {
    if (_loading) {
      return loadingWidget(_loading);
    } else {
      return ListView(
        children: <Widget>[
          Container(
            padding: EdgeInsets.all(8),
            child: TextField(
              controller: controller,
              keyboardType: TextInputType.multiline,
              decoration: InputDecoration(
                hintText: '请输入你的病情描述',
                border: InputBorder.none,
              ),
              minLines: 3,
              maxLines: 8,
            ),
          ),
          SizedBox(height: 20),
          Container(
            padding: EdgeInsets.all(8),
            child: GridView.count(
              physics: new NeverScrollableScrollPhysics(),
              shrinkWrap: true,
              crossAxisSpacing: 10.0,
              mainAxisSpacing: 10.0,
              crossAxisCount: 3,
              childAspectRatio: 1.0,
              children: getWidgetList(),
            ),
          )
        ],
      );
    }
  }

  // 回到帖子详情页面
  _entryPostDetaiPage() {
    Navigator.pop(context);
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        onWillPop: () async {
          if (lastPopTime == null ||
              DateTime.now().difference(lastPopTime) > Duration(seconds: 1)) {
            //两次点击间隔超过1秒则重新计时
            lastPopTime = DateTime.now();
            openAlertDialog(
                context, _entryPostDetaiPage, '确认退出编辑，一旦退出，一切将不予保存');
            return new Future.value(false);
          }
          return new Future.value(true);
        },
        child: Scaffold(
          appBar: AppBar(
            centerTitle: true,
            title: Text(widget.postID != null ? '修改帖子' : '增加帖子'),
            actions: <Widget>[
              GestureDetector(
                  onTap: _submit,
                  child: Flex(
                    direction: Axis.vertical,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Container(
                        margin: EdgeInsets.only(right: 10),
                        child: Text('发布', style: TextStyle(fontSize: 18)),
                      )
                    ],
                  ))
            ],
          ),
          body: _childLayout(),
        ));
  }

  // 在提交后进行的操作
  _afterSubmit(int code, String errorMsg, String successMsg) {
    if (code == 0) {
      successToast(successMsg);
    } else {
      errorToast(errorMsg);
    }
    Navigator.pop(context); // 退出加载中弹窗
    Navigator.pop(context); // 退出编辑页面
  }

  // 发布信息
  _submit() async {
    print(controller.text); // 清空imagePicker获取到的图片
    print(postImages); // TODO: 将其与上面的拼接在一起
    showDialog(
        context: context,
        builder: (context) {
          return new AboveLoading();
        });
    if (widget.postID == null) {
      dynamic res = await addPost_api('$backIP/post/addPost', {
        'content': controller.text,
        'files': postImages,
      });
      _afterSubmit(res['code'], '增加成功', res['message']);
    } else {
      dynamic res = await alterPost_api('$backIP/post/updatePost', {
        'postId': widget.postID,
        'content': controller.text,
        'files': postImages,
      });
      _afterSubmit(res['code'], '修改成功', res['message']);
    }
  }
}
